package com.xbongbong.paas.script.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsInitByCorpidListAndBusinessTypeListDTO;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsInitDTO;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsMappingDTO;
import com.xbongbong.paas.pojo.dto.PaasFormOriginalDataInitDTO;
import com.xbongbong.paas.pojo.dto.PrintLogDTO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsInitVO;
import com.xbongbong.paas.service.PaasElasticSearchService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.IndexTypeModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * Paas数据的初始化
 * 创建时间： 2018/9/27 14:33
 * 修改时间： 2018/9/27 14:33 梁鲁江
 *
 * @author 梁鲁江
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/esInit")
public class PaasElasticSearchInit {
    @Resource
    private PaasElasticSearchService paasElasticSearchService;
    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;

    private static final Logger LOG = LoggerFactory.getLogger(PaasElasticSearchInit.class);
    @Resource
    private IndexTypeModel indexTypeModel;

    /**
     * paas初始化数据
     * @param paasFormDataEsInitDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/formDataInit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String formDataInit(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.init(paasFormDataEsInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 团队成员需求用于paas表单提前刷数据
     * @param paasFormDataEsInitDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/teamMembersPaasFormDataInit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String teamMembersPaasFormDataInit(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.teamMembersPaasFormDataInit(paasFormDataEsInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * paas初始化数据
     * @param paasFormDataEsInitByCorpidListAndBusinessTypeListDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/formDataInitByCorpidListAndBusinessTypeList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String formDataInitByCorpidListAndBusinessTypeList(@RequestBody @Valid PaasFormDataEsInitByCorpidListAndBusinessTypeListDTO paasFormDataEsInitByCorpidListAndBusinessTypeListDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitByCorpidListAndBusinessTypeListDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.initByCorpidListAndBusinessTypeList(paasFormDataEsInitByCorpidListAndBusinessTypeListDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    /**
     * 慎用
     * 初始化主type和team(paas和其他子type除外)
     * @param paasFormDataEsInitDTO
     * @param br
     * @return
     * @throws Exception
     */
    @Deprecated
    @RequestMapping(value = "/formDataInitAll", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String formDataInitAll(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.initAll(paasFormDataEsInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    @Deprecated
    @RequestMapping(value = "/initAllByBuss", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String initAllByBuss(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.initAllByBuss(paasFormDataEsInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    /**
     * saas初始化数据
     * @param paasFormDataEsInitDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saasDataInit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String saasDataInit(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.initSaasData(paasFormDataEsInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * paas团队成员（这边主要指的是paas协同人表）同步
     *  curl http://127.0.0.1:2019/pro/v1/esInit/paasTeamDataInit -X POST -H 'Content-type: application/json' -d '{"frontDev":"1","xbbCode":"123456","corpid":"1","userId":"1","platform":"web","saasMark":2,"businessType":100301,"byCorpid":1,
     *  "formId":39397, "appId":4468, "updateTimeStart":1639719417}'
     * @param paasFormDataEsInitDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/paasTeamDataInit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String paasTeamDataInit(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.paasTeamDataInit(paasFormDataEsInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * paas初始化mapping
     * @param paasFormDataEsMappingDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/formDataMapping", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String formDataMapping(@RequestBody @Valid PaasFormDataEsMappingDTO paasFormDataEsMappingDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsMappingDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
//                PaasFormDataEsInitVO paasFormDataEsInitVO = paasElasticSearchService.initMapping(paasFormDataEsMappingDTO);
                PaasFormDataEsInitVO paasFormDataEsInitVO = paasElasticSearchService.initHighMapping(paasFormDataEsMappingDTO);
                response = new XbbResponse<>(paasFormDataEsInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/formDataMappingDelete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String formDataMappingDelete(@RequestBody @Valid PaasFormDataEsMappingDTO paasFormDataEsMappingDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsMappingDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                BaseVO baseVO = paasElasticSearchService.deleteMapping(paasFormDataEsMappingDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/formDataMappingAll", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String formDataMappingAll(@RequestBody @Valid PaasFormDataEsMappingDTO paasFormDataEsMappingDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsMappingDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasFormDataEsInitVO = paasElasticSearchService.initMappingAll(paasFormDataEsMappingDTO);
                response = new XbbResponse<>(paasFormDataEsInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    
    @RequestMapping(value = "/formStaticsData", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String formStaticsData(@RequestBody @Valid PaasFormDataEsMappingDTO paasFormDataEsMappingDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;
        
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsMappingDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasFormDataEsInitVO = paasElasticSearchService.initHighMappingTest(paasFormDataEsMappingDTO);
                response = new XbbResponse<>(paasFormDataEsInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    
    /**
     * saas初始化mapping
     * @param paasFormDataEsMappingDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saasDataMapping", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String saasDataMapping(@RequestBody @Valid PaasFormDataEsMappingDTO paasFormDataEsMappingDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsMappingDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.initSaasMapping(paasFormDataEsMappingDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    @RequestMapping(value = "/setPrintLog", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String setPrintLog(@RequestBody @Valid PrintLogDTO printLogDTO, BindingResult br) throws Exception {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(printLogDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                xbbElasticsearchRestTemplate.setPrintLog(printLogDTO.getPrintLog());
                response = new XbbResponse<>(printLogDTO.getPrintLog().toString());
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 对应删除es中的数据和sql脚本

     DELETE FROM tb_paas_form_data WHERE corpid = '159'

     DELETE FROM tb_saas_customer WHERE corpid = '159'
     DELETE FROM tb_saas_customer_user WHERE corpid = '159'

     DELETE FROM tb_saas_contract WHERE corpid = '159'
     DELETE FROM tb_saas_contract_user WHERE corpid = '159'
     DELETE FROM tb_saas_contract_product WHERE corpid = '159'
     DELETE FROM tb_saas_contract_performance WHERE corpid = '159'

     DELETE FROM tb_saas_quotation WHERE corpid = '159'
     DELETE FROM tb_saas_quotation_user WHERE corpid = '159'

     DELETE FROM tb_saas_outstock WHERE corpid = '159'

     DELETE FROM tb_saas_contact WHERE corpid = '159'
     DELETE FROM tb_saas_contact_user WHERE corpid = '159'

     DELETE FROM tb_saas_invoice WHERE corpid = '159'

     DELETE FROM tb_saas_instock WHERE corpid = '159'

     DELETE FROM tb_saas_assemble WHERE corpid = '159'

     DELETE FROM tb_saas_quotation_user WHERE corpid = '159'
     DELETE FROM tb_saas_outstock WHERE corpid = '159'

     DELETE FROM tb_saas_payment WHERE corpid = '159'
     DELETE FROM tb_saas_payment_user WHERE corpid = '159'

     DELETE FROM tb_saas_payment_sheet WHERE corpid = '159'

     DELETE FROM tb_saas_pay_sheet WHERE corpid = '159'


     DELETE FROM tb_saas_production_order WHERE corpid = '159'
     DELETE FROM tb_saas_production_order_user WHERE corpid = '159'

     DELETE FROM tb_saas_pay_plan WHERE corpid = '159'
     DELETE FROM tb_saas_pay_plan_user WHERE corpid = '159'

     DELETE FROM tb_saas_communicate_plan WHERE corpid = '159'
     DELETE FROM tb_saas_communicate_plan_user WHERE corpid = '159'

     DELETE FROM tb_saas_opportunity WHERE corpid = '159'
     DELETE FROM tb_saas_opportunity_user WHERE corpid = '159'

     DELETE FROM tb_saas_bom WHERE corpid = '159'
     DELETE FROM tb_saas_bom_user WHERE corpid = '159'

     DELETE FROM tb_saas_customer_communicate WHERE corpid = '159'
     DELETE FROM tb_saas_supplier_communicate WHERE corpid = '159'



     DELETE FROM tb_saas_work_report WHERE corpid = '159'


     DELETE FROM tb_saas_purchase WHERE corpid = '159'
     DELETE FROM tb_saas_purchase_user WHERE corpid = '159'

     DELETE FROM tb_saas_returned_purchase WHERE corpid = '159'


     DELETE FROM tb_saas_supplier_contact WHERE corpid = '159'
     DELETE FROM tb_saas_supplier_contact_user WHERE corpid = '159'

     DELETE FROM tb_saas_supplier WHERE corpid = '159'
     DELETE FROM tb_saas_supplier_user WHERE corpid = '159'

     DELETE FROM tb_saas_product WHERE corpid = '159'
     DELETE FROM tb_saas_product_user WHERE corpid = '159'
     DELETE FROM tb_saas_product_warehouse WHERE corpid = '159'
     DELETE FROM tb_saas_product_stock_info WHERE corpid = '159'


     DELETE FROM tb_saas_inventory WHERE corpid = '159'


     DELETE FROM tb_saas_transfer WHERE corpid = '159'

     DELETE FROM tb_saas_warehouse WHERE corpid = '159'


     DELETE FROM tb_saas_refund WHERE corpid = '159'
     DELETE FROM tb_saas_refund_user WHERE corpid = '159'


     DELETE FROM tb_saas_work_order_data WHERE corpid = '159'
     DELETE FROM tb_work_order_flow_user WHERE corpid = '159'
     DELETE FROM tb_work_order_cc WHERE corpid = '159'
     DELETE FROM tb_work_order_evaluation WHERE corpid = '159'

     DELETE FROM tb_call_center_call_log WHERE corpid = '159'

     DELETE FROM tb_payment_balance WHERE corpid = '159'
     DELETE FROM tb_payment_balance_user WHERE corpid = '159'
     * @param paasFormDataEsInitDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delAllDataByCorpid", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String delAllDataByCorpid(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.deleteAllData(paasFormDataEsInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    @RequestMapping(value = "/queryTest", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String queryTest(@RequestBody @Valid PrintLogDTO transChartDTO, BindingResult br) {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            // ----------------------------------repeat post----------------------------------------------
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(transChartDTO.getIgnoreConCheck())) {
                //重复提交校验
            }
            // ----------------------------------repeat post----------------------------------------------
            try {
                //验证码
                if(!proBaseConfig.getXbbCode().equals(transChartDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword",transChartDTO.getCorpid()));
                IndexTypeEnum customerIndex = indexTypeModel.getCustomerIndex(transChartDTO.getCorpid(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, customerIndex.getType()));
                sourceBuilder.query(boolQueryBuilder);
                //分页
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 1);
                SearchRequest searchRequest = new SearchRequest(customerIndex.getIndex());
                searchRequest.source(sourceBuilder);
                XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest, PaasFormDataEntityExt.class);
                if (esEntities == null) {
                    LOG.error("=============查不到");
                }
                List<PaasFormDataEntityExt> resultList = new ArrayList<>(esEntities.getContent());
                if(CollectionsUtil.isNotEmpty(resultList)){
                    PaasFormDataEntityExt paasFormDataEntityExt = resultList.get(0);
                    LOG.info("============="+ paasFormDataEntityExt.toString()+ paasFormDataEntityExt.getFormId()+ "_"+paasFormDataEntityExt.getAddTime());
                }
                response = new XbbResponse<>("");
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 添加别名
     * @param paasFormDataEsMappingDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addAlias", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public String addAlias(@RequestBody @Valid PaasFormDataEsMappingDTO paasFormDataEsMappingDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsMappingDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasFormDataEsInitVO = paasElasticSearchService.addAlias(paasFormDataEsMappingDTO);
                response = new XbbResponse<>(paasFormDataEsInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
    @RequestMapping(value = "/addAllAlias", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public String addAllAlias(@RequestBody @Valid PaasFormDataEsMappingDTO paasFormDataEsMappingDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsMappingDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasFormDataEsInitVO = paasElasticSearchService.addAllAlias(paasFormDataEsMappingDTO);
                response = new XbbResponse<>(paasFormDataEsInitVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    @RequestMapping(value = "/originDataInit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public String originDataInit(@RequestBody @Valid PaasFormOriginalDataInitDTO paasFormOriginalDataInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;

        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormOriginalDataInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.initOriginData(paasFormOriginalDataInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    @RequestMapping(value = "/subDataInit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String subDataInit(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.initSubData(paasFormDataEsInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * paas子表单数据同步，只限于团队成员需求使用，切忌乱使用
     * 如有同步paas子表单的需求请使用  curl  http://127.0.0.1:2019/pro/v1/esInit/initAllByBuss  -X POST -H 'Content-type: application/json' -d '{"userId":"1","corpid":"1","platform":"web","xbbCode":"123456","saasMark":1,"businessType":2,"byCorpid":0,"businessTypeList":[2], "include":true}'
     *
     * @param paasFormDataEsInitDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/paasSubDataInit", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String paasSubDataInit(@RequestBody @Valid PaasFormDataEsInitDTO paasFormDataEsInitDTO, BindingResult br) throws Exception {
        XbbResponse<PaasFormDataEsInitVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsInitDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                PaasFormDataEsInitVO paasPrintSaveVO = paasElasticSearchService.initPaasSubData(paasFormDataEsInitDTO);
                response = new XbbResponse<>(paasPrintSaveVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }


    /**
     * 删除线上paas的es索引，切记只用于团队成员需求，后续不能再用这个脚本
     *
     * @param paasFormDataEsMappingDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/formDataPaasMappingDelete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String formDataPaasMappingDelete(@RequestBody @Valid PaasFormDataEsMappingDTO paasFormDataEsMappingDTO, BindingResult br) throws Exception {
        XbbResponse<BaseVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsMappingDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                BaseVO baseVO = paasElasticSearchService.deletePaasMapping(paasFormDataEsMappingDTO);
                response = new XbbResponse<>(baseVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 主要是为了灰度环境上校验数据量，因为kibina在灰度环境
     *
     * @param paasFormDataEsMappingDTO
     * @param br
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/checkEsDataNum", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String checkEsDataNum(@RequestBody @Valid PaasFormDataEsMappingDTO paasFormDataEsMappingDTO, BindingResult br) throws Exception {
        XbbResponse<String> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                if(!proBaseConfig.getXbbCode().equals(paasFormDataEsMappingDTO.getXbbCode())){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006, SystemErrorCodeEnum.API_ERROR_100006.getMsg());
                }
                String str = paasElasticSearchService.checkEsDataNum(paasFormDataEsMappingDTO);
                response = new XbbResponse<>(str);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }

}
